/**
 * Created by Administrator on 2017/5/16.
 */
import * as express from "express";
import {Server} from "ws"
const app=express();

app.get("/", (req,res)=>{
  res.send("hello express")
})
export class Produce{
  constructor(
    public id:number,
    public title:string,
    public price:number,
    public rating:number,
    public desc:string,
    public categories:Array<string>
  ){}
}
const products:Produce[] =[
  new Produce(1,"第一个商品",1.99,3.5,"这是第一个商品描述",["图书","音乐"]),
  new Produce(2,"第二个商品",3.99,2.5,"这是第二个商品描述",["语文"]),
  new Produce(3,"第三个商品",4.99,4.5,"这是第三个商品描述",["音乐","体育"]),
  new Produce(4,"第四个商品",5.99,1.5,"这是第四个商品描述",["化学","体育"]),
  new Produce(5,"第五个商品",16.99,4.5,"这是第五个商品描述",["生物","图书"]),
  new Produce(6,"第六个商品",12.99,3.5,"这是第六个商品描述",["科学"]),
]

export class Comment{
  constructor(
    private id:number,
    public produceId:number,
    public timestamp:string,
    public user:string,
    public rating:number,
    public content:string
  ){}
}
const comments:Comment[]=[
  new Comment(1,1,'2017-2-2 2:2:2','张三',3,"东西不错"),
  new Comment(2,1,'2017-2-3 22:12:22','张三',3,"东西不错"),
  new Comment(3,1,'2017-2-4 12:12:12','张三',2,"东西不错"),
  new Comment(4,2,'2017-2-5 2:2:2','张三',4,"东西不错"),

]
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.get("/api/products",(req,res)=>{
  res.json(products)
});

app.get("/api/products/:id",(req,res)=>{
  //在命令行中打印,当发送个请求的时候才触发,
  // console.log(req.params)
  res.json(products.find( produce => produce.id==req.params.id))
});

app.get("/api/products/:id/comments",(req,res)=>{
  //在命令行中打印,当发送个请求的时候才触发,
  // console.log(req.params)
  res.json(comments.filter((comment)=> comment.produceId == req.params.id))
});

//启动服务器 相当于apache开启了
const server =app.listen(8000,"localhost",()=>{
  console.log("服务器已经启动,地址ffff是http://localhost:8000")
});
//在全局创建Server
const wsServer =new Server({port :8085});
//当连接的时候,服务器向客户端推送消息 ,已经客户端向服务器发送的消息
wsServer.on("connection",websocket=>{
  websocket.send("这个消息是来自webscort主动推送的",()=>{
    console.log(wsServer)
  });
  websocket.on("message",(message)=>{

    console.log(message)
  })
});
//定时向客户端发送消息,实时出价系统也是用定时器的
setInterval(()=>{
  if(wsServer.clients){
    wsServer.clients.forEach(client=>{
      client.send(products);
    })
  }
},2000);